﻿/**
 * Author:feitianxinhong
 * CreateData: 2014-11-08
 * Description:开发者中心主页
 */

var Tyingsoft = Tyingsoft || {};
Tyingsoft.SDK = {
    Vars: {
        topMenuActiveItem: null, //当前激活的主菜单项
        isFullScreen: 0,  //当前主内容是否全屏（1：是  0：否）
        activeTabPanelId: '',    //当前激活菜单内容内的id（注：包含#号）
        twiSkin: ''      //当前主题
    }//end Vars

    , init: function () {
        $(document).bind("contextmenu", function (e) {
            return false;
        });

        twiSelf.reloadTopMenu();
        $('#topLogout').click(twiSelf.loginout);
        $('#topSet').click(function () {
            $('#topSetItem').slideToggle(400);
        });
        $('#ModuleSelect').click(function () {
            $('#topSetItem').slideUp("slow");
        });
        $('#EditPwd').click(function () {
            $('#topSetItem').slideUp("slow");
        });

        //回到常用导航菜单
        $('#navTitle').click(function () {
            twiSelf.reloadMyComPlug();
        });

        //解决IE7、360浏览器高度不能自适应问题
        $('#theMain').height($(document).height() - 80);

        //$('#hideMenu').twiDropdown();

        //常用模块设置
        $('#ModuleSelect').click(function () {
            //添加或激活Tab页
            twiSelf.addOrActiveTabItem("ModuleSelect", "常用模块设置", "/BIM/ModuleSelect/Index");
        });

        twiSelf.initTabDropMenuEvent();
        //加载默认主页
        twiSelf.loadHomeTab();

        //内容全屏（最大化）最小化事件
        twiSelf.Touch.initTouchAction();

        //Twi概念主题
        twiSelf.Skin.init();

    } //end init

    /*加载默认主页*/
    , loadHomeTab: function () {
        var tabPanelId = "tabPanel_home";
        var html = '<div role="tabPanel" id="' + tabPanelId + '">';
        var autoHeight = $(window).height() - 83;
        html += '<iframe id="theMain" name="theMain" width="100%" height="' + autoHeight + '" frameborder="0" src="DeskTop.html" scrolling="no"></iframe>';
        html += '</div>   '
        $('#center').append(html);
    }//end loadHomeTab


    /**
    *  获取功能模块列表
    */
    , reloadTopMenu: function () {
        Twi.Ajax({
            data: {
                mn: 'Portal',
                cn: 'ConfigData',
                mn2: 'GetData',
                data: JSON.stringify({
                    Code: 'SDKModules',
                    ConfigDataFile: 'sdk'
                })
            },
            success: function (twi) {
                $('#topMenu').html('');
                var hideMenuUL = $('#hideMenuContainer ul[to="hideMenu"]').empty();
                if (twi.totalCount == 0) {
                    Twi.Msg.Info('未找到任何可用的功能模块！');
                    return;
                }
                for (var i in twi.data) {
                    var item = twi.data[i];
                    //取前三个功能模块加载到topMenu
                    if (i < 5) {
                        src = "themes/blue/images/tab_close.png"
                        //$('#topMenu').append('<div class="menuItem" navName="' + item.Name + '" entityID="' + item.ID + '">' + item.Name + '<div class="tabCloseIcon"></div></div>');
                        //为了兼容IE7,把 <div class="tabCloseIcon"></div> 改成<img class="tabCloseIcon" src="themes/blue/images/tab_close.png"/>
                        //这样.tabCloseIcon 就可以去掉影响IE7显示不正确的float:right;
                        $('#topMenu').append('<div class="menuItem" id="tab_mn_' + item.ID + '" navName="' + item.Name + '" entityID="' + item.ID + '">' + item.Name + '<img class="tabCloseIcon" src="themes/common/images/tab_close.png"/></div>');
                    }
                    hideMenuUL.append('<li><a entityID="' + item.ID + '">' + item.Name + '</a></li>');
                }
                twiSelf.initFirstMenuAction();
            }
        });

    } //end reloadTopMenu

    /**
     * 初始化Tab右键菜单事件
     */
    , initTabDropMenuEvent: function () {
        //关闭当前
        $('#tdmCloseThis').click(function () {
            $(twiVars.topMenuActiveItem).find('.tabCloseIcon').click();
            //关闭右键菜单(自身)
            $(this).parent().hide();
        });

        //关闭所有
        $('#tdmCloseAll').click(function () {
            $('#topMenu .menuItem').find('.tabCloseIcon').click();
            //关闭右键菜单(自身)
            $(this).parent().hide();
        });

        //除此之外全部关闭
        $('#tdmCloseBesideThis').click(function () {
            $('#topMenu .menuItem').each(function () {
                if ($(this).attr('id') != $(twiVars.topMenuActiveItem).attr('id')) {
                    $(this).find('.tabCloseIcon').click();
                }
            });
            //关闭右键菜单(自身)
            $(this).parent().hide();
        });

        //取消事件
        $('#tdmCancel').click(function () {
            $(this).parent().hide();
        });
    }//end 

    /**
    * 初始化一级菜单事件
    */
    , initFirstMenuAction: function () {
        $('#topMenu .menuItem').mouseup(function (e) {
            $('#topMenu div').removeClass('current');
            $(this).addClass('current');
            $('#navTitle').html($(this).attr('navName'));
            //动态加载左侧导航
            twiSelf.reloadLeftNav($(this).attr('entityID'));

            if (e.which == "3") //鼠标右键
            {
                $('#tabDropMenu ul').show();
                $('#tabDropMenu .tabDropdownMenu').css({
                    left: e.pageX,
                    top: e.pageY
                });
                e.stopPropagation();
            }
            //当前激活的主菜单项
            twiVars.topMenuActiveItem = $(this);

        }).hover(function () {
            //$(this).find('.tabCloseIcon').css('height', '16px');
            $(this).find('.tabCloseIcon').css({
                'height': '16px',
                'filter': 'alpha(opacity=100)',
                '-moz-opacity': '1',
                '-khtml-opacity': '1',
                'opacity': '1'
            });
        }, function () {
            //$(this).find('.tabCloseIcon').css('height', '1px');
            $(this).find('.tabCloseIcon').css({
                'height': '1px',
                'filter': 'alpha(opacity=0)',
                '-moz-opacity': '0',
                '-khtml-opacity': '0',
                'opacity': '0'
            });
        }).find('.tabCloseIcon').click(function () {
            $(this).parent().remove();
        });

        $('#hideMenuContainer ul[to="hideMenu"] li a').click(function () {
            $('#navTitle').html($(this).html());
            //动态加载左侧导航
            twiSelf.reloadLeftNav($(this).attr('entityID'));

        });

    } //end initFirstMenuAction

    /**
    *根据功能模块ID，动态加载左侧导航
    */
    , reloadLeftNav: function (plugType) {
        if ($('#leftNav').attr('plugType') == plugType) {
            //如果是一样的就不需要去加载数据了
            return;
        }
        Twi.Ajax({
            data: {
                cn: 'ConfigData',
                mn: 'Portal',
                mn2: 'GetData',
                data: JSON.stringify({
                    Code: 'SDKMenu',
                    ConfigDataFile: 'sdk',
                    ChildName: 'Menu',
                    ChildCode:plugType
                })                
            },
            success: function (twi) {
                $('#leftNav').attr('plugType', plugType).html('');
                for (var i in twi.data) {
                    var item = twi.data[i];
                    if (item.Children && item.Children.length > 0) {
                        //有子菜单
                        var html = "<div>";
                        html += '<div class="navItem collapsed hasChildren">' + item.Name + '</div>'
                        html += '<ul>';
                        for (var j in item.Children) {
                            var child = item.Children[j];
                            var navItmNum = parseInt(j) + 1;
                            navItmNum = navItmNum < 10 ? '0' + navItmNum : navItmNum;
                            navItmNum += '.';
                            var id = "mu_"+item.ID + "_" + child.ID;
                            html += '<li><div class="navItem child"><a id="' + id + '" url="' + child.Url + '" navName="' + child.Name + '" IsYoudaoNote="' + child.IsYoudaoNote + '"><div>' + navItmNum + child.Name + '</div></a></div></li>'
                        }
                        html += '</ul>';
                        html += '</div>';
                        $('#leftNav').append(html);
                    }
                    else {
                        var id = "mu_" + item.ID;
                        $('#leftNav').append('<div><div class="navItem"><a id="' + id + '" url="' + item.Url + '" navName="' + item.Name + '" IsYoudaoNote=' + item.IsYoudaoNote + '"><div>' + item.Name + '</div></a></div></div>')
                    }
                }

                //初始化左侧导航事件
                twiSelf.initLeftNavAction();
            }
        });
    }

    /*加载我的常用导航*/
    , reloadMyComPlug: function () {
        if ($('#leftNav').attr('plugType') == "") {
            //如果是一样的就不需要去加载数据了
            return;
        }
        $('#navTitle').html('我的常用导航');
        Twi.Ajax({
            data: {
                cn: 'Authority',
                mn: 'BIM',
                mn2: 'GetMyCommPlug'
            },
            success: function (twi) {
                $('#leftNav').attr('plugType', "").html('');
                for (var i in twi.data) {
                    var item = twi.data[i];
                    var id = item.PLUGCODE + "_" + item.ID;
                    $('#leftNav').append('<div><div class="navItem"><a id="' + id + '" url="' + item.PLUGURL + '" navName="' + item.PLUGNAME + '"><div>' + item.PLUGNAME + '</div></a></div></div>');
                }

                //初始化左侧导航事件
                twiSelf.initLeftNavAction();
            }
        });
    }

    /**
    *  初始化左侧导航事件
    */
    , initLeftNavAction: function () {
        $('#leftNav ul').hide();
        $('#leftNav .hasChildren').click(function () {
            $(this).next('ul').toggle(400);
            $(this).toggleClass("expand");
        });
        $('#leftNav a').click(function () {
            $('#leftNav div').removeClass('current');
            $(this).parent('div').addClass('current');

            //添加或激活Tab页
            twiSelf.addOrActiveTabItem($(this).attr("id"), $(this).attr('navName'), $(this).attr('url'), $(this).attr('IsYoudaoNote'));
        });
    } //end initLeftNavAction

    /**
    * 添加或激活Tab页
    * @idPostfixCode : id后缀        【规则】
    * @tabTitle : tab标题            【添加Tab页的时候需要该参数】
    * @url ：tab内容的ifame地址      【添加Tab页的时候需要该参数】
    * @isYoudaoNoet：是否采用有道云笔记的方式。【如果是，会自动对有道云笔记做处理】
    */
    , addOrActiveTabItem: function (idPostfixCode, tabTitle, url,isYoudaoNote) {
        $('#topMenu div').removeClass('current');
        var topMenuItemId = "tab_" + idPostfixCode;
        if ($('#' + topMenuItemId).length == 0) {
            //$('#topMenu').append('<div id="' + topMenuItemId + '" idPostfixCode="' + idPostfixCode + '" class="menuItem current">' + tabTitle + '<div class="tabCloseIcon"></div></div>');
            tabTitle = tabTitle.length > 10 ? tabTitle.substring(0, 8)+"..." : tabTitle;
            $('#topMenu').append('<div id="' + topMenuItemId + '" idPostfixCode="' + idPostfixCode + '" class="menuItem current">' + tabTitle + '<img class="tabCloseIcon" src="themes/common/images/tab_close.png"/></div>');

            //Tab页单击切换事件
            $('#' + topMenuItemId).mouseup(function (e) {
                $('#topMenu div').removeClass('current');
                $(this).addClass('current');

                //显示tabPanel的内容
                $('#center').find('div[role="tabPanel"]').hide();
                $('#tabPanel_' + $(this).attr("idPostfixCode")).show();

                if (e.which == "3") //鼠标右键
                {
                    $('#tabDropMenu ul').show();
                    $('#tabDropMenu .tabDropdownMenu').css({
                        left: e.pageX,
                        top: e.pageY
                    });
                    e.stopPropagation();
                }
                //当前激活的主菜单项
                twiVars.topMenuActiveItem = $(this);

            }).hover(function () {
                //$(this).find('.tabCloseIcon').css('height', '16px');
                $(this).find('.tabCloseIcon').css({
                    'height': '16px',
                    'filter': 'alpha(opacity=100)',
                    '-moz-opacity': '1',
                    '-khtml-opacity': '1',
                    'opacity': '1'
                });
            }, function () {
                //$(this).find('.tabCloseIcon').css('height', '1px');
                $(this).find('.tabCloseIcon').css({
                    'height': '1px',
                    'filter': 'alpha(opacity=0)',
                    '-moz-opacity': '0',
                    '-khtml-opacity': '0',
                    'opacity': '0'
                });
            }).find('.tabCloseIcon').click(function () {
                var isActive = $(this).parent().hasClass('current');
                $('#tabPanel_' + $(this).parent().attr("idPostfixCode")).remove();
                $(this).parent().remove();

                //如果关闭的Tab页为激活页，那么将激活页设置为最后一个
                if (isActive) {
                    var lastTab = $('#topMenu').children('.menuItem').last().addClass('current');
                    if (lastTab.length > 0) {
                        $('#tabPanel_' + $(lastTab).attr("idPostfixCode")).show();
                    }
                }
            });

            $('#center').find('div[role="tabPanel"]').hide();
            var tabPanelId = "tabPanel_" + idPostfixCode;
            var html = '<div role="tabPanel" id="' + tabPanelId + '">';
            var autoHeight = $(window).height() - 83;
            var iframeId = "ifm_" + tabPanelId;
            html += '<iframe name="theMain" id="'+iframeId+'"  width="100%" height="' + autoHeight + '" frameborder="0" src="' + url + '" scrolling="no"></iframe>';
            html += '</div>   '
            $('#center').append(html);

            //存储当前激活菜单内容内的id（注：包含#号）
            twiVars.activeTabPanelId = tabPanelId;

            //有道云笔记
            if (isYoudaoNote) {
                twiSelf.youdaoNoteHandler(iframeId);
            }
        }
        else {
            $('#' + topMenuItemId).addClass('current');

            //显示tabPanel的内容
            $('#center').find('div[role="tabPanel"]').hide();
            var tabPanelId = "#tabPanel_" + idPostfixCode;
            $(tabPanelId).show();

            //存储当前激活菜单内容内的id（注：包含#号）
            twiVars.activeTabPanelId = tabPanelId;
        }

    } //end addOrActiveTabItem

    /*有道云笔记处理*/
    , youdaoNoteHandler: function (iframeId) {
        //$('#' + iframeId).contents().find("#nw_head_menu").parent().remove();

    }//end YoudaoNoteHandler
    
    /*全屏模式切换*/
    , Touch: {
        /*初始化事件*/
        initTouchAction: function () {
            $('#touchFullScreen').click(function () {
                if (twiVars.isFullScreen) {
                    twiSelf.Touch.exitFullScreen();
                    twiVars.isFullScreen = 0;
                }
                else {
                    twiSelf.Touch.fullScreen();
                    twiVars.isFullScreen = 1;
                }
            });
        }//end initTouchAction

        /*内容全屏*/
        , fullScreen: function () {
            $('#center').css({
                "top": 0,
                "left": 0
            });
            $('#touch').css({
                "top": 5
            });
            $('iframe[name="theMain"]').each(function (index, elm) {
                var height = parseInt($(this).attr('height'));
                $(this).attr('height', height + 80);
            });
        } //end fullScreen

        /*内容退出全屏*/
        , exitFullScreen: function () {
            $('#center').css({
                "top": 80,
                "left": 236
            });
            $('#touch').css({
                "top": 85
            });

            $('iframe[name="theMain"]').each(function (index, elm) {
                var height = parseInt($(this).attr('height'));
                $(this).attr('height', height - 80);
            });
        }//end exitFullScreen

    }//end Touch


    /*Twi概念主题*/
    , Skin: {
        /**
         * 获取当前主题名
         */
        getCurrent: function () {
            var skinName = window.localStorage.tyingSoftSDKSkin; //Cookies.get('twiSkin');
            if (!skinName) {
                //未设置则为随机选定主题
                var twiSkins = ['turquoise', 'sunorange', 'dreamblue', 'amethyst', 'emerland', 'rainright', 'alizarin', 'brown'];
                var nRandom = Math.floor(100 * Math.random()); // 这里返回 [0,99]                 
                var index = nRandom % twiSkins.length;
                skinName = twiSkins[index];
            }
            return skinName;
        }//end getCurrent

        /**
         * 初始化
         */
        , init: function () {
            //切换到当前主题
            twiVars.twiSkin = twiSelf.Skin.getCurrent();
            twiSelf.Skin.change(twiVars.twiSkin);

            var modal = $('#twiSkinModal');
            $('#topSkin').click(function () {
                //随机效果
                var nRandom = Math.floor(100 * Math.random()); // 这里返回 [0,99]                 
                var index = nRandom % 11;
                $('#twiSkinModal').removeClass().addClass('twi-md-modal twi-md-effect-' + (index + 1));
                modal.addClass('twi-md-show');
            });
            //关闭/保存按钮
            $('#twiSkinSave').click(function (ev) {
                ev.stopPropagation();
                modal.removeClass('twi-md-show');
            });
            //点击标题也关闭，为兼容老浏览器可能看不到关闭按钮
            $('#twiSkinTitle').click(function (ev) {
                ev.stopPropagation();
                modal.removeClass('twi-md-show');
            })

            //选择事件
            $('#skinContainer').children('.skinItem').click(function () {
                $('#skinContainer').children('.skinItem').removeClass('skinSlt').css('border-color', 'transparent');
                var color = $(this).children('.skinColor2').first().html();
                $(this).addClass('skinSlt').css('border-color', color);

                //更换主题
                var twiSkin = $('#skinContainer').children('.skinSlt').children('.skinCode').html();
                twiSelf.Skin.change(twiSkin);
            });

        }//end init

        /**
         * 变更主题
         */
        , change: function (twiSkin) {
            //更换Twi概念主题
            $('link[twiSkin]').remove();
            $('head').append('<link href="themes/' + twiSkin + '/Home.css" twiSkin="' + twiSkin + '" rel="stylesheet" />');
            $('#twiSkinModal .twi-md-content').removeClass().addClass('twi-md-content twi-md-bg-' + twiSkin);
            $('#twiSkinSave').removeClass().addClass('twi-md-btn twi-md-close twi-md-btn-' + twiSkin);

            //保持主题至Cookie
            //Cookies.set('twiSkin', twiSkin);
            window.localStorage.tyingSoftSDKSkin = twiSkin;
        }//end change

    } //end Skin

} //end Tyingsoft.SDK

var twiSelf = Tyingsoft.SDK;
var twiVars = twiSelf.Vars;


